package com.awz.manage.aop.Log;
/*
 * @author  LiangYu
 * @date  2022/1/5 11:48
 * @Email:salong0503@aliyun.com
 */

import com.awz.manage.aop.annotation.MyLog;
import com.awz.manage.entities.JournalInfo;
import com.awz.manage.service.JournalInfoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


/*
*
*
* private Integer id;
  private String operator;
  private Date time;
  private String ipAddr;
  private String module;
  private String detail;
* */
@Aspect
@Component
@Slf4j
public class LogAspect {
	
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private JournalInfoService sysLogService;
	
	//指定使用注解切入点
	@Pointcut("@annotation(com.awz.manage.aop.annotation.MyLog)")
	public void logPointcut() {
	}
	
	@Around("logPointcut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
//		Object[] args = point.getArgs();
//		Object result = point.proceed(args);
		Object result = null;
		try {
			result = point.proceed();
			if (saveLog(point) > 0) {
				log.info("记录日志成功!");
			}
		} catch (Throwable e) {
			log.error(e.getMessage());
		}
		return result;
	}
	
	private int saveLog(ProceedingJoinPoint point) throws JsonProcessingException {
		JournalInfo sysLog = new JournalInfo();
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method method = signature.getMethod();
		//通过方法获取注解
		MyLog annotation = method.getAnnotation(MyLog.class);
		if (annotation != null) {
			//通过注解过去到value里面的描述
			sysLog.setOperator(annotation.value());
			sysLog.setModule(annotation.model());
			//记录详细操作 使用El表达式
			sysLog.setDetail(annotation.detail());
		}
		
		//获取用户名
		//需要根据权限token来做,暂时无法实现
		//获取ip
		
		String ip = request.getRemoteAddr();//后续可优化
		sysLog.setIpAddr(ip);
		return sysLogService.createSysLog(sysLog);
	}
	
	
}
